/**
 * 并发控制
 */

class Request{
    constructor({limt=4}){
        this.limt = limt
        this.resolveArr = [] // 收集resolve
        this.currIndex = 0
    }

    async request(fun){
        if(typeof fun !== 'function') {
            throw new Error('is not Function')
        };
        if(this.currIndex >= this.limt){
            await new Promise((resolve)=>{this.resolveArr.push(resolve)}) 
        }
        return this.handle(fun)
    }

    async handle(fun){
        this.currIndex++
        try{
            return await fun()
        }catch(e){
            return Promise.reject(e)
        }finally{
            this.currIndex--
            if(this.resolveArr.length){
                this.resolveArr[0]()
                this.resolveArr.shift()
            }
        }
    }
}


// 模拟请求过程
function fetch(i){
    return new Promise((resolve, reject)=>{
        var time = Math.random() * 1000 * 5
        console.log('请求:' + i)
        setTimeout(()=>{
            console.log('请求:' + i + '----')
            resolve(time)
        }, time)
    })
}

const request = new Request({limt:4})
debugger
for(let i = 0; i < 10; i++){
    request.request(async function(){
        await fetch(i)
        // console.log('fetch:',)
    })
}
